package com.itheima.pinda.config;

import com.itheima.pinda.service.NettyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * netty服务器启动类
 *
 * @author llhuang10
 * @date 2021/10/21 10:20
 */
@Slf4j
@Component
public class NettyServer implements CommandLineRunner {


    private static NettyServer nettyServer;
    @Value("${netty.port}")
    private int port;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private ServerBootstrap bootstrap;
    private ChannelFuture future;


    public NettyServer() {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();

        bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .option(ChannelOption.SO_BACKLOG, 128) //设置缓存
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .channel(NioServerSocketChannel.class)
                .childHandler(new NettyServerHandler()); // 具体处理网络IO事件
    }

    public void start() {
        // 启动server服务端, 绑定端口
        try {
            this.future = bootstrap.bind(nettyServer.port).sync();
            log.info("Netty Server 启动完毕!!! 端口: {}", nettyServer.port);
        } catch (InterruptedException e) {
            log.error("netty服务启动异常-" + e.getMessage());
        }
    }


    /**
     *
     */
    @PostConstruct
    public void init() {
        nettyServer = this;
    }

    @Override
    public void run(String... args) throws Exception {
        this.start();
    }
}
